/**
 * Copyright &copy; 2012-2014 <a href="https://github.com/thinkgem/jeesite">JeeSite</a> All rights reserved.
 */
package com.youngball.web.controller;

import com.github.pagehelper.Page;
import com.youngball.business.utill.Code;
import com.youngball.business.utill.DateUtils;
import com.youngball.shiro.entity.ActiveUser;
import org.apache.commons.lang3.StringEscapeUtils;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.subject.Subject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.InitBinder;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.beans.PropertyEditorSupport;
import java.io.IOException;
import java.util.*;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

@Controller
public abstract class BaseController {

	public static final Logger logger1 = LoggerFactory.getLogger("myTest1");

	/**
	 * 客户端返回JSON字符串

	 * @return
	 */

	@SuppressWarnings("Duplicates")
	Map responce2Client(String code,String msg,Map data)
    {
        Map maps = new HashMap( );
        maps.put("code",code);
        maps.put("msg",msg);
        maps.put("data",data);
        return maps;
    }

	@SuppressWarnings("Duplicates")
	public  Map responce2Client(String code, String msg, Object data)
	{
		Map maps = new HashMap( );
		maps.put("code",code);
		maps.put("msg",msg);
		maps.put("data",data);
		return maps;
	}

	@ExceptionHandler(Exception.class)
	public ResponseEntity<Map> operateExp(RuntimeException ex, HttpServletRequest request){
		Map maps=new HashMap();
		ex.printStackTrace();
		if ("com.youngball.business.exception.MyDefineException".equals(ex.getClass().getName())){
			maps.put("msg", ex.getMessage());
		}else {
			maps.put("msg", "操作失败");
			ExecutorService executorService = Executors.newCachedThreadPool();
//			executorService.execute(new MailUtilsSend(request,ex));
		}
		maps.put("code", Code.DEFAI.toString());
		return new ResponseEntity<Map>(maps, HttpStatus.OK);
	}

	public ResponseEntity<Map> buildResult(Object data, String code){
		Map maps=new HashMap();
		maps.put("code", code);
		maps.put("data",data);
		return new ResponseEntity<Map>(maps, responseHeaders, HttpStatus.OK);
	}

	public ResponseEntity<Map> buildResult(Object data){
		Map maps=new HashMap();
		maps.put("code",Code.SUC.toString());
		maps.put("msg", "操作成功");
		maps.put("data",data);
		return new ResponseEntity<Map>(maps, responseHeaders, HttpStatus.OK);
	}
	public ResponseEntity<Map> buildResult(){
		Map maps=new HashMap();
		maps.put("code", Code.SUC.toString());
		maps.put("msg", "操作成功");
		return new ResponseEntity<Map>(maps, responseHeaders, HttpStatus.OK);
	}

	public ResponseEntity<Map> buildResult(String code, String msg, HttpStatus statusCode){
		Map maps=new HashMap();
		maps.put("code",code);
		maps.put("msg",msg);
		return new ResponseEntity<Map>(maps, responseHeaders, statusCode);
	}

	/**
	 * 组装分页条件参数公共方法
	 * @return
	 */
	public Map<String,Object> assembledParameter(int pageIndex,int pageSize,Object...objects){
		Map<String,Object> map=new HashMap();
		map.put("pageIndex",pageIndex);
		map.put("pageSize",pageSize);
		return map;
	}

	/**
	 * 组装分页条件参数公共方法
	 * @return
	 */
	public Map<String,Object> assembledParameter(String likeString,int pageIndex,int pageSize){
		Map<String,Object> map=new HashMap();
		map.put("likeString",likeString);
		map.put("pageIndex",pageIndex);
		map.put("pageSize",pageSize);
		return map;
	}

	/**
	 * 组装分页返回值json参数
	 * @return
	 */
	public LinkedHashMap<String,Object> assembledPagination(int pageindex, int pageSize, long totalItems){
		LinkedHashMap<String,Object> pagination = new LinkedHashMap<String,Object>();
		pagination.put("pageIndex",pageindex);
		pagination.put("pageSize",pageSize);
		pagination.put("totalItems",totalItems);
		return pagination;
	}

	/**
	 * 组装结果集Json参数
	 * @param page
	 * @param list
     * @return
     */
	public Map assembledResult(Page page , List<?> list){
		LinkedHashMap<String,Object> pagination = assembledPagination(page.getPageNum(),
				page.getPageSize(),
				page.getTotal());
		Map result = new LinkedHashMap();
		result.put("pagination",pagination);
		result.put("data",list);
		return result;
	}

    protected static HttpHeaders responseHeaders;
    static {

        responseHeaders = new HttpHeaders();
        responseHeaders.set("Access-Control-Allow-Origin", "*");
        responseHeaders.set("Access-Control-Allow-Methods", "GET,POST,PUT,DELETE,OPTIONS");
        responseHeaders.set("Access-Control-Allow-Credentials", "true");
        responseHeaders.set("Access-Control-Max-Age", "60");
    }
	/*protected String renderString(HttpServletResponse response, Object object) {
		return renderString(response, JsonMapper.toJsonString(object), "application/json");
	}
	*/
	/**
	 * 客户端返回字符串
	 * @param response
	 * @param string
	 * @return
	 */
	protected String renderString(HttpServletResponse response, String string, String type) {
		try {
			response.reset();
	        response.setContentType(type);
	        response.setCharacterEncoding("utf-8");
			response.getWriter().print(string);
			return null;
		} catch (IOException e) {
			return null;
		}
	}
	@InitBinder
	protected void initBinder(WebDataBinder binder) {
		// String类型转换，将所有传递进来的String进行HTML编码，防止XSS攻击
		binder.registerCustomEditor(String.class, new PropertyEditorSupport() {
			@Override
			public void setAsText(String text) {
				setValue(text == null ? null : StringEscapeUtils.escapeHtml4(text.trim()));
			}
			@Override
			public String getAsText() {
				Object value = getValue();
				return value != null ? value.toString() : "";
			}
		});

		// Date 类型转换
		binder.registerCustomEditor(Date.class, new PropertyEditorSupport() {
			@Override
			public void setAsText(String text) {
				setValue(DateUtils.parseDate(text));
			}

		});

	}

	public ActiveUser getCurrentUser(){
		Subject subject = SecurityUtils.getSubject();
		ActiveUser activeUser = (ActiveUser)subject.getPrincipal();
		return activeUser;
	}
	
}
